﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using THS.HtmlHelpers;
using Veteran_cms.Models;

namespace Veteran_cms.Controllers
{
    public class ManageNewsController : BaseController
    {
        private const string Status = "active";
        readonly Veterandb _ctx = new Veterandb();
        //
        // GET: /ManageAbout/
        const int PageSize = 6;
        public ActionResult IndexNews(int page = 1)
        {
            var model = new HomeAdminListViewModel();
            var newsArticle = _ctx.news_article.OrderByDescending(p => p.article_id).ToList();
            model.NewsArticles = newsArticle.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.NewsArticlePageInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = newsArticle.Count() };
            return View(model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Paging(int page = 1)
        {
            var model = new HomeAdminListViewModel();
            var newsArticle = _ctx.news_article.OrderByDescending(p => p.article_id).ToList();
            model.NewsArticles = newsArticle.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.NewsArticlePageInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = newsArticle.Count() };
            return PartialView("UCNewsList", model);
        }

        public ActionResult Details(int id)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            var ctg = _ctx.news_article.SingleOrDefault(c => c.article_id == id);
            if (ctg != null)
            {
                InitParentCategory(ctg.category_id);
                return View(ctg);
            }
            else
            {
                ctg = new news_article();
                InitParentCategory(ctg.category_id);
                return View(ctg);
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Details(int id, HttpPostedFileBase uploadFile)
        {
            try
            {
                // TODO: Add update logic here
                // if (!IsAuthenticateAdmin())
                //   return RedirectToAction("LogOn", "AdminHome");
                var oldImage = string.Empty;
                var oldThumbImage = string.Empty;
                var news = _ctx.news_article.SingleOrDefault(p => p.article_id == id);
                var changeImage = false;
                if (uploadFile != null)
                {
                    if (news.article_id > 0)
                    {
                        oldImage = news.image_large;
                        oldThumbImage = news.image_thumbnail;
                    }
                    var fileName = Path.GetFileName(uploadFile.FileName);
                    var sFileName = GenerateFileNameByNo(Request, Utilities.VirtualPath, fileName, DateTime.Now.ToString("yyyyMMddhhmmss"));
                    var filePath = Path.Combine(Request.MapPath(Utilities.VirtualPath), sFileName);
                    var fileThumbPath = Path.Combine(Request.MapPath(Utilities.VirtualPath + "Thumbs/"), sFileName);
                    ResizeImage(uploadFile.InputStream, fileThumbPath, 99, 99, true);
                    ResizeImage(uploadFile.InputStream, filePath, 400, 300, true);
                    news.image_large = Utilities.PhysicalPath + sFileName;
                    news.image_thumbnail = String.Format("{0}Thumbs/{1}", Utilities.PhysicalPath, sFileName);
                    changeImage = true;
                }
                if (news != null)
                {
                    news.updated_date = DateTime.Now;
                    news.status = Status;
                    UpdateModel(news);
                    var newsHot = _ctx.news_article_hot.SingleOrDefault(x => x.article_id == news.article_id);
                    if (news.is_hot == true && newsHot == null)
                        _ctx.AddTonews_article_hot(new news_article_hot { article_id = news.article_id, created_date = news.created_date });
                    if (news.is_hot == false && newsHot != null)
                        _ctx.news_article_hot.DeleteObject(newsHot);
                }
                _ctx.SaveChanges();
                if (changeImage)
                {
                    if (!string.IsNullOrEmpty(oldImage))
                        DeleteFile(Request, Utilities.VirtualPath, oldImage);
                    if (!string.IsNullOrEmpty(oldThumbImage))
                        DeleteFile(Request, Utilities.VirtualPath + "Thumbs", oldThumbImage);
                }
                InitParentCategory(news != null ? news.category_id : 0);
                ViewData["Msg"] = "Đã cập nhật!";
                return View(news);
            }
            catch
            {
                ViewData["Msg"] = "Đã có lỗi xẩy ra. Vui lòng kiểm tra lại dữ liệu!";
                InitParentCategory(string.Empty);
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            // TODO: Add delete logic here
            //if (!IsAuthenticateAdmin())
            //    return RedirectToAction("LogOn", "AdminHome");
            if (id <= 0)
                return RedirectToAction("Create", "ManageNews", new news_article());
            var news = _ctx.news_article.SingleOrDefault(p => p.article_id == id);
            var assocs = _ctx.news_article_category_assoc.Where(n => n.article_id == news.article_id);
            _ctx.DeleteObject(news);
            foreach (var assoc in assocs)
            {
                _ctx.DeleteObject(assoc);
            }
            _ctx.SaveChanges();
            DeleteFile(Request, Utilities.VirtualPath, news.image_large);
            DeleteFile(Request, Utilities.VirtualPath + "Thumbs", news.image_thumbnail);
            return RedirectToAction("IndexNews");
        }

        public ActionResult Create()
        {
            var news = new news_article { is_hot = false };
            news.show_date = DateTime.Now.Date;
            InitParentCategory(new category());
            return View(news);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create([Bind(Exclude = "article_id")]news_article news, HttpPostedFileBase uploadFile, FormCollection collection)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            try
            {
                if (uploadFile != null)
                {
                    var fileName = Path.GetFileName(uploadFile.FileName);
                    var sFileName = GenerateFileNameByNo(Request, Utilities.VirtualPath, fileName,
                                                         DateTime.Now.ToString("yyyyMMddhhmmss"));
                    var filePath = Path.Combine(Request.MapPath(Utilities.VirtualPath), sFileName);
                    var fileThumbPath = Path.Combine(Request.MapPath(Utilities.VirtualPath + "Thumbs/"), sFileName);
                    //MakeImagesAndThumbFile(uploadFile.InputStream, filePath, fileThumbPath, 400, 300, 90, 99, 75);
                    //save thumbnail file
                    ResizeImage(uploadFile.InputStream, fileThumbPath, 99, 99, true);
                    ResizeImage(uploadFile.InputStream, filePath, 400, 300, true);
                    news.image_large = Utilities.PhysicalPath + sFileName;
                    news.image_thumbnail = String.Format("{0}Thumbs/{1}", Utilities.PhysicalPath, sFileName);
                }
                news.created_date = DateTime.Now;
                news.updated_date = DateTime.Now;
                news.status = Status;
                _ctx.AddTonews_article(news);
                _ctx.SaveChanges();

                if (news.category_id != null)
                {
                    var assoc = new news_article_category_assoc { article_id = news.article_id, category_id = news.category_id.Value };
                    _ctx.news_article_category_assoc.AddObject(assoc);
                }
                if (news.is_hot == true)
                {
                    var newsHot = _ctx.news_article_hot.SingleOrDefault(x => x.article_id == news.article_id);
                    if (newsHot == null)
                    {
                        _ctx.AddTonews_article_hot(new news_article_hot { article_id = news.article_id, created_date = news.created_date });
                    }
                }
                //tag
                var keys = collection.Keys.Cast<string>().Where(x => x.StartsWith("hd"));
                foreach (string key in keys)
                {

                    int tagId;
                    var stringId = collection[key];
                    if (int.TryParse(stringId, out tagId))
                    {
                        //save tag
                        var item = new tag_item_assoc { item_id = news.article_id,tag_id = tagId, @params = "News" };
                        _ctx.tag_item_assoc.AddObject(item);
                    }
                    _ctx.SaveChanges();
                }
                ViewData["Msg"] = "Đã tạo thành công!";
                return RedirectToAction("IndexNews");
            }
            catch
            {
                ViewData["Msg"] = "Đã có lỗi xẩy ra. Vui lòng kiểm tra lại dữ liệu!";
                InitParentCategory("");
                return View(string.Empty);
            }
        }

        //#region --Utitlies-
        private void InitParentCategory(object selected)
        {
            var ctg = _ctx.categories.ToList();
            ctg.Insert(0, new category());
            ViewData["categoryPanrent"] = new SelectList(ctg.AsEnumerable(), "category_id", "name", selected);
        }

        [HttpPost]
        public JsonResult FindTexts(string searchText, int maxResults)
        {
            var autoComplete = new TagAutoComplete();
            var result = autoComplete.FindPeople(searchText, maxResults);
            return Json(result);
        }
    }
}
